# coding: utf-8
import re
import time
from globals import *
import time,datetime
import csv
# Set up the path to the .NET Framework.
import sys
sys.path.append(r'C:\Windows\Microsoft.NET\Framework\v4.0.30319')

# Make clr accessible.
import clr

# Add any required references.
clr.AddReference('System.Windows.Forms.DLL')

# Import the .NET assemblies.
import System
import System.Windows.Forms

from form import *
from System.Windows.Forms import MessageBox

Ether_Type=["IpV4","TCP","UDP"]
import threading
tree_msg = []
No = [0]
# Define the event handlers.
def btnConnect_Click(*args):
  '''
   这是个connect就是等待接受send发送的数据怎增加了5s的延时
  '''
  a = str(WMPForm.inputArea.Rows[0].Cells[0].Value)
  # 获取对应数据
  new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
  destination = MAC.index(WMPForm.inputArea.Rows[2].Cells[0].Value)
  send = a
  receive = str(andi.TestProject.ChannelAdapters[destination])
  source_ip = new_index.get_ip()
  destination_ip = andi.TestProject.ChannelAdapters[destination].get_ip()
  if WMPForm.inputArea.Rows[6].Cells[0].Value==None:
       MessageBox.Show("please input the value of cyclic period, in ms")
       return
  else: 
       interval=int(WMPForm.inputArea.Rows[6].Cells[0].Value)  
        
  if WMPForm.inputArea.Rows[7].Cells[0].Value==None:
       MessageBox.Show("please input the value of repitition No.")
       return
  else: 
       repitition=int(WMPForm.inputArea.Rows[7].Cells[0].Value)
  time_stamp = []
  def reading_read():
    msg_eth=message_builder.create_ethernet_message(send,receive)  #1.创建一个以太网消息 映射一个channel Adapter.默认情况下，是第一个channel Adaptuers
    #time_stamp = []
    def on_message_recevied(msg):                           # 2. 定义一个回调函数。为什么必须要有参数
        a = str(WMPForm.inputArea.Rows[0].Cells[0].Value)
        new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
        if str(msg.mac_address_source) == WMPForm.inputArea.Rows[1].Cells[0].Value:
            No[0] = No[0] + 1
            #print No[0]
            #print '----------',msg.timestamp ,'--------------'            
            WMPForm.inputArea.Rows[5].Cells[0].Value = msg.payload.LongLength
            time_stamp.append(msg.timestamp)
            #这个是main界面中的length
            #print msg.get_bytes().Length
            msg.payload.Length
            # 这个是time
            msg.timestamp
            dest_ip = WMPForm.inputArea.Rows[3].Cells[0].Value
            Time = msg.timestamp - time_stamp[0]
            a = str(WMPForm.inputArea.Rows[0].Cells[0].Value)
            new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
  
            #WMPForm.inputArea.Rows[1].Cells[0].Value = new_index.get_mac()            
            WMPForm.DataArea.Rows.Add(
              No[0],Time,new_index.get_ip(),dest_ip,
              WMPForm.inputArea.Rows[3].Cells[0].Value,msg.payload.Length,WMPForm.textBox1.Text)
        
        else:
            pass      
    msg_eth.on_message_received+=on_message_recevied        # 3. 将回调函数赋予给on_message_received事件

    msg_eth.start_capture()                                 # 4.开始从bus上捕捉。 哪个bus
    #print 5+int(WMPForm.inputArea.Rows[6].Cells[0].Value)
    time.sleep(5+int(WMPForm.inputArea.Rows[7].Cells[0].Value))                                          # 5.捕捉的时间

    msg_eth.on_message_received-=on_message_recevied        # 6.将函数从事件从事件触发中取消

    msg_eth.stop_capture()                                  # 7.借宿捕捉
  t1 = threading.Thread(target=reading_read) 
  t1.start()
    
def btnClear_Click(*args):
    '''
        清空所有数据
    '''
    No[0] = 0
    #print time_stamp
    WMPForm.DataArea.Rows.Clear()
    
def btnSave_Click(*args):
    '''
         把数据写入.csv的表格内
    '''
    #print No[0]
    data = []
    for list in range(No[0]):
        li = []
        for line in range(7):
            li.append(WMPForm.DataArea.Rows[list].Cells[line].Value)
            #print WMPForm.DataArea.Rows[list].Cells[line].Value
        data.append(li)
    now = datetime.datetime.now()
    filename = str(now.year)+str(now.month)+str(now.day)+str(now.hour)+str(now.minute)+str(now.second)+'-EntMsg'+'.csv'
    #print type(filename)
    path = 'C:/Users/jason/Desktop/'+filename
    #print path
    file = open(path, 'wb')
    csv_writer = csv.writer(file)
    # 行写入
    csv_writer.writerow(['No.','Time','Source','Destination','Protocol','Length','Info'])
    for  i in data:
        csv_writer.writerow(i)

def btnSend_Click(*args):
    '''
        数据的发送
    '''
    a = str(WMPForm.inputArea2.Rows[0].Cells[0].Value)
    # 获取对应数据
    new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
    destination = MAC.index(WMPForm.inputArea2.Rows[2].Cells[0].Value)
    send = a
    receive = str(andi.TestProject.ChannelAdapters[destination])
    source_ip = new_index.get_ip()
    destination_ip = WMPForm.inputArea.Rows[3].Cells[0].Value
    No[0] = 0
    WMPForm.DataArea.Rows.Clear()
    e = WMPForm.inputArea.Rows[4].Cells[0].Value
    mac_src=WMPForm.inputArea.Rows[1].Cells[0].Value
    mac_dst=WMPForm.inputArea.Rows[2].Cells[0].Value
    eth_type=WMPForm.inputArea.Rows[4].Cells[0].Value
    send_content=WMPForm.textBox1.Text
    #print mac_src,mac_dst,eth_type,send_content
    
    if WMPForm.inputArea.Rows[6].Cells[0].Value==None:
       MessageBox.Show("please input the value of cyclic period, in ms")
       return
    else: 
        interval=int(WMPForm.inputArea.Rows[6].Cells[0].Value)  
        
    if WMPForm.inputArea.Rows[7].Cells[0].Value==None:
       MessageBox.Show("please input the value of repitition No.")
       return
    else: 
        repitition=int(WMPForm.inputArea.Rows[7].Cells[0].Value)
    def send_msg(): 
        if e == 'IpV4':
            msg_eth=message_builder.create_ip_message(send,send)
           # msg_eth.ether_type=EtherType.IpV4
            
            msg_eth.ethernet_header.mac_address_destination = str(WMPForm.inputArea.Rows[2].Cells[0].Value)
            msg_eth.ip_header.ip_address_destination = str(WMPForm.inputArea.Rows[3].Cells[0].Value)
            #msg_eth.
        if e == 'UDP':
             
             msg_eth = message_builder.create_udp_message(send,send)
             
             msg_eth.ip_header.ip_address_source = source_ip 
             msg_eth.ethernet_header.mac_address_source = WMPForm.inputArea.Rows[1].Cells[0].Value
  
             msg_eth.ethernet_header.mac_address_destination = str(WMPForm.inputArea.Rows[2].Cells[0].Value)
             msg_eth.ip_header.ip_address_destination = destination_ip 
        
             msg_eth.transport_header.port_source = WMPForm.inputArea.Rows[8].Cells[0].Value
             msg_eth.transport_header.port_destination = WMPForm.inputArea.Rows[9].Cells[0].Value
             
                
        if e == 'TCP':    
            msg_eth = message_builder.create_tcp_message(send,send)
            
            msg_eth.ethernet_header.mac_address_destination = str(WMPForm.inputArea.Rows[2].Cells[0].Value)
            msg_eth.ip_header.ip_address_destination = destination_ip 
            
            msg_eth.transport_header.port_source = WMPForm.inputArea.Rows[8].Cells[0].Value
            msg_eth.transport_header.port_destination = WMPForm.inputArea.Rows[9].Cells[0].Value
               
            #msg_eth.connect()
            
            
        if WMPForm.textBox1.Text:
            if len(send_content)%2 == 0:
                # 写出正则表达式 任意2个字符
                pattern = re.compile('.{2}')
                pay_load = ','.join(pattern.findall(send_content))
            else: 
                pattern = re.compile('.{2}')
                pay_load = ','.join(pattern.findall(send_content+'0'))
            if len(send_content) > 2:
                msg_eth.payload=System.Array[Byte](eval(pay_load))    #简单设置报文
            else:
                msg_eth.payload=System.Array[Byte]([eval(pay_load)])
        
        else:
            pass
        tree_msg.append(msg_eth.tree_view())

        def on_time_elapsed(a,b):                               # why a,b
            msg_eth.send()
            #print 'sending'

        g_timer_1.on_time_elapsed += on_time_elapsed
        g_timer_1.interval = int(WMPForm.inputArea.Rows[6].Cells[0].Value) # 时间间隔周期
        g_timer_1.start()
        
        time.sleep(int(WMPForm.inputArea.Rows[7].Cells[0].Value))

        g_timer_1.stop()
        g_timer_1.on_time_elapsed -= on_time_elapsed
    t2 = threading.Thread(target=send_msg) 
    t2.start()
def cbCell_leave(*args):
        a = str(WMPForm.inputArea.Rows[0].Cells[0].Value)
        # 获取对应数据
        new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
        #print andi.TestProject.ChannelAdapters
        WMPForm.inputArea.Rows[1].Cells[0].Value = new_index.get_mac()
                
        #if WMPForm.inputArea.Rows[3].Cells[0].Value == 'UDP' or WMPForm.inputArea.Rows[3].Cells[0].Value == 'TCP':
        if WMPForm.inputArea.Rows[4].Cells[0].Value == 'TCP' or WMPForm.inputArea.Rows[4].Cells[0].Value == 'UDP':
            WMPForm.inputArea.Size = System.Drawing.Size(580, 260)
            WMPForm.inputArea.RowCount = 10
            WMPForm.inputArea.Rows[7].HeaderCell.Value = "Repetition No."  
            WMPForm.inputArea.Rows[8].HeaderCell.Value = "Port Source"
            WMPForm.inputArea.Rows[9].HeaderCell.Value = "Port Destination"
            WMPForm.inputArea.Rows[8].Cells[0].Value = 40499
            WMPForm.inputArea.Rows[9].Cells[0].Value = 40499
        else:
            WMPForm.inputArea.Size = System.Drawing.Size(580, 210)
            WMPForm.inputArea.RowCount = 8
            WMPForm.inputArea.Rows[7].HeaderCell.Value = "Repetition No."
def btna2send_Click(*args):
    a = str(WMPForm.inputArea2.Rows[0].Cells[0].Value)
    # 获取对应数据
    new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
    destination = MAC.index(WMPForm.inputArea2.Rows[2].Cells[0].Value)
    send = a
    receive = str(andi.TestProject.ChannelAdapters[destination])
    source_ip = new_index.get_ip()
    destination_ip = andi.TestProject.ChannelAdapters[destination].get_ip()
    if WMPForm.inputArea2.Rows[6].Cells[0].Value==None:
       MessageBox.Show("please input the value of cyclic period, in ms")
       return
    else: 
        interval=int(WMPForm.inputArea2.Rows[6].Cells[0].Value)  
        
    if WMPForm.inputArea2.Rows[7].Cells[0].Value==None:
       MessageBox.Show("please input the value of repitition No.")
       return
    else: 
        repitition=int(WMPForm.inputArea2.Rows[6].Cells[0].Value)
    def someip_send():
        a = str(WMPForm.inputArea2.Rows[0].Cells[0].Value)
        new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
        msg_someip=message_builder.create_someip_message()
        msg_someip.ethernet_header.mac_address_destination = WMPForm.inputArea2.Rows[2].Cells[0].Value
        msg_someip.ethernet_header.mac_address_source = WMPForm.inputArea2.Rows[1].Cells[0].Value
        msg_someip.ip_header.ip_address_destination =destination_ip
        msg_someip.ip_header.ip_address_source = source_ip
        msg_someip.transport_header.port_destination = int(WMPForm.inputArea2.Rows[10].Cells[0].Value)
        msg_someip.transport_header.port_source = int(WMPForm.inputArea2.Rows[11].Cells[0].Value)
        
        msg_someip.someip_header.method_identifier = eval(WMPForm.inputArea2.Rows[9].Cells[0].Value)
        msg_someip.someip_header.protocol_version = eval(WMPForm.inputArea2.Rows[12].Cells[0].Value)
        msg_someip.someip_header.interface_version = eval(WMPForm.inputArea2.Rows[13].Cells[0].Value)
        msg_someip.someip_header.message_type = MessageType.REQUEST
        msg_someip.someip_header.return_code = ReturnCode.E_OK
        if WMPForm.inputArea2.Rows[14].Cells[0].Value:
            msg_someip.vlan_tag.inner_vlan = int(WMPForm.inputArea2.Rows[14].Cells[0].Value)
        else:
            pass
        if WMPForm.inputArea2.Rows[15].Cells[0].Value:
            msg_someip.vlan_tag.outer_vlan = int(WMPForm.inputArea2.Rows[15].Cells[0].Value)
        else:
            pass
        
        
        #msg_someip.payload = System.Array[Byte]([0x0c, 0x04, 0x5d])
        if WMPForm.page2textBox1.Text:
            send_content = WMPForm.page2textBox1.Text
            if len(send_content)%2 == 0:
                # 写出正则表达式 任意2个字符
                pattern = re.compile('.{2}')
                pay_load = ','.join(pattern.findall(send_content))
            else: 
                pattern = re.compile('.{2}')
                pay_load = ','.join(pattern.findall(send_content+'0'))
            if len(send_content) > 2:
                msg_someip.payload=System.Array[Byte](eval(pay_load))    #简单设置报文
            else:
                msg_someip.payload=System.Array[Byte]([eval(pay_load)])
        
        else:
            pass
        # 数据长度64bit
        WMPForm.inputArea2.Rows[5].Cells[0].Value = msg_someip.payload.LongLength
        def on_time_elapsed(a,b):
                msg_someip.send()

        g_timer_2.on_time_elapsed += on_time_elapsed
        g_timer_2.interval = int(WMPForm.inputArea2.Rows[6].Cells[0].Value)
        g_timer_2.start()

        time.sleep(int(WMPForm.inputArea2.Rows[7].Cells[0].Value))

        g_timer_2.stop()
        g_timer_2.on_time_elapsed -= on_time_elapsed
        
    #print threading.activeCount()
    if threading.activeCount() == 1:
        t2 = threading.Thread(target=someip_send) 
        t2.start()
    else:
        pass
    
def inputArea2_Click(*args):
    a = str(WMPForm.inputArea2.Rows[0].Cells[0].Value)
    # 获取对应数据
    new_index =(andi.TestProject.ChannelAdapters)[list.index(a)]
    destination = MAC.index(WMPForm.inputArea2.Rows[2].Cells[0].Value)
    send = a
    receive = str(andi.TestProject.ChannelAdapters[destination])
    destination_ip = new_index.get_ip()
    source_ip = andi.TestProject.ChannelAdapters[destination].get_ip()
    #print send,send_ip,receive,receive_ip
    WMPForm.inputArea2.Rows[1].Cells[0].Value = new_index.get_mac()

def DataArea_Click(*args):
    if tree_msg:
        WMPForm.textBox2.Text = tree_msg[-1]
    else:
        pass

# Define the Windows Form and the elements of this specific instance.
WMPForm = form()
WMPForm.InitializeComponent()

#initialize data
'''
    WMPForm.cbCell.DataSource=Des
    WMPForm.cbCell.Value=Des[0]
    WMPForm.inputArea.Rows[1].Cells[0].Value=MACs[0]
'''
WMPForm.cbCel2.DataSource=Ether_Type
WMPForm.cbCel2.Value=Ether_Type[0]
WMPForm.inputArea.Rows[4].Cells[0].Value=Ether_Type[0]

connertor = andi.TestProject.ChannelAdapters[0]
connertor2 = andi.TestProject.ChannelAdapters[1]
list =[]
'''
    这里不能用适配网口写入。net界面，必须用字符串方式写入
'''
MAC = []
for i in andi.TestProject.ChannelAdapters:
    #print type(i.get_mac())
    #WMPForm.inputArea.Rows[2].Cells[0].Items.Add(i.get_mac())
   # WMPForm.inputArea2.Rows[2].Cells[0].Items.Add(i.get_mac())
    list.append(str(i)) 
    MAC.append(i.get_mac())
#print MAC
# 以字符串的格式写入 .NET 界面 
for li in list:
    WMPForm.inputArea2.Rows[0].Cells[0].Items.Add(li)
    WMPForm.inputArea.Rows[0].Cells[0].Items.Add(li)
WMPForm.inputArea.Rows[0].Cells[0].Value = list[0]
WMPForm.inputArea2.Rows[0].Cells[0].Value = list[0]
WMPForm.inputArea2.Rows[1].Cells[0].Value = connertor.get_mac()
WMPForm.inputArea.Rows[3].Cells[0].Value = connertor2.get_ip()
WMPForm.inputArea.Rows[2].Cells[0].Value = connertor2.get_mac()
WMPForm.inputArea2.Rows[2].Cells[0].Value = connertor2.get_mac()
WMPForm.inputArea2.Rows[3].Cells[0].Value = connertor2.get_ip()
WMPForm.inputArea.Rows[1].Cells[0].Value = connertor.get_mac()
WMPForm.inputArea.Rows[4].Cells[0].Value=Ether_Type[0]
chouse_adapters = WMPForm.inputArea.Rows[0].Cells[0].Value
#msg_eth=message_builder.create_ethernet_message(chouse_adapters,chouse_adapters)

# Always add event handlers after defining the Windows Form.
WMPForm.btnConnect.Click += btnConnect_Click
WMPForm.btnClear.Click += btnClear_Click
WMPForm.btnSave.Click += btnSave_Click
WMPForm.btnSend.Click += btnSend_Click
WMPForm.inputArea.Click += cbCell_leave
WMPForm.btn2send.Click += btna2send_Click
WMPForm.inputArea2.Click += inputArea2_Click
WMPForm.DataArea.Click += DataArea_Click


# Run the application.
System.Windows.Forms.Application.Run(WMPForm)

